package com.software.loginregister.fragment.community;


import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;

import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.software.loginregister.R;
import com.software.loginregister.activity.RecommendDetailActivity;
import com.software.loginregister.activity.SearchActivity;
import com.software.loginregister.adapter.PostAdapter;
import com.software.loginregister.api.LikeApi;
import com.software.loginregister.api.PostApi;

import com.software.loginregister.entity.Post;
import com.software.loginregister.entity.Result;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import lombok.NonNull;
import retrofit2.Call;
import retrofit2.Response;


import com.software.loginregister.util.RetrofitClient;

import retrofit2.Callback;

public class RecommendCommunityFragment extends Fragment {
    private RecyclerView rvPosts;
    private PostAdapter adapter;
    private List<Post> posts;
    private TextView tvCommunityRecommendSearch;
    private TextView tvCommunityRecommendSearchBtn;
    private SwipeRefreshLayout swipeRefreshLayout;
    private int currentPage = 1;
    private static final int PAGE_SIZE = 20;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_recommend_community, container, false);
        posts = new ArrayList<>();
        initViews(view);
        setupListeners();
        loadData();
        return view;
    }

    private void loadData() {
        RetrofitClient.getInstance()
                .create(PostApi.class)
                .getRecommendedPosts(currentPage, PAGE_SIZE)
                .enqueue(new Callback<Result<List<Post>>>() {
                    @Override
                    public void onResponse(Call<Result<List<Post>>> call, Response<Result<List<Post>>> response) {
                        Log.d(TAG, "onResponse: " + response.code()+" ,"+response.body()+",response.isSuccessful "+response.isSuccessful());
                        if (response.isSuccessful() && response.body() != null) {
                            Result<List<Post>> result = response.body();
                            if (result.getCode() == 1 && result.getData() != null) {
                                List<Post> newPosts = result.getData();
                                // 添加数据检查日志
                                for (Post post : newPosts) {
                                    Log.d(TAG, "Post data: " +
                                            "\nTitle: " + post.getPostTitle() +
                                            "\nText: " + post.getPostText() +
                                            "\nAvatar: " + post.getAvatar() +
                                            "\nImage: " + post.getPostImage());
                                }
                                if (currentPage == 1) {
                                    posts.clear();
                                }
                                posts.addAll(newPosts);
                                adapter.notifyDataSetChanged();
                            } else {
                                Log.e(TAG, "加载帖子失败: " + result.getMsg());
                                Toast.makeText(getContext(), "加载帖子失败: " + result.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Log.e(TAG, "加载帖子失败: 服务器错误 " + response.code());
                            Toast.makeText(getContext(), "加载帖子失败: 服务器错误", Toast.LENGTH_SHORT).show();
                        }
                        swipeRefreshLayout.setRefreshing(false);
                    }

                    @Override
                    public void onFailure(Call<Result<List<Post>>> call, Throwable t) {
                        Log.e(TAG, "加载帖子失败: 网络错误", t);
                        Toast.makeText(getContext(), "加载帖子失败: 网络错误", Toast.LENGTH_SHORT).show();
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
    }

    private void initViews(View view) {
        // 初始化搜索相关视图
        tvCommunityRecommendSearch = view.findViewById(R.id.tv_community_recommend_search);
        tvCommunityRecommendSearchBtn = view.findViewById(R.id.tv_community_recommend_search_btn);

        //下拉刷新
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
        swipeRefreshLayout.setColorSchemeResources(R.color.theme_color);
//        swipeRefreshLayout.setOnRefreshListener(() -> loadRecipeData(false));
        // 初始化RecyclerView
        rvPosts = view.findViewById(R.id.rv_recommend_posts);
        rvPosts.setLayoutManager(new LinearLayoutManager(getContext()));
        posts = new ArrayList<>();
        adapter = new PostAdapter(getContext(), posts);
        rvPosts.setAdapter(adapter);

        swipeRefreshLayout.setOnRefreshListener(() -> {
            currentPage = 1;
            loadData();
        });

        // 添加滚动监听器以实现分页加载
        rvPosts.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int visibleItemCount = layoutManager.getChildCount();
                int totalItemCount = layoutManager.getItemCount();
                int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();

                if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                        && firstVisibleItemPosition >= 0
                        && totalItemCount >= PAGE_SIZE) {
                    currentPage++;
                    loadData();
                }
            }
        });
    }

    private void setupListeners() {
        tvCommunityRecommendSearch.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), SearchActivity.class);
            startActivity(intent);
        });

        tvCommunityRecommendSearchBtn.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), SearchActivity.class);
            startActivity(intent);
        });
    }


}